package com.purchase.ml.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.purchase.ml.bean.req.sys.SysRoleEditDto;
import com.purchase.ml.bean.req.sys.SysRoleNewDto;
import com.purchase.ml.bean.req.sys.SysRoleQueryDto;
import com.purchase.ml.entity.sys.SysRole;
import com.purchase.ml.enums.SysSeqNameEnum;
import com.purchase.ml.mapper.sys.SysRoleMapper;
import com.purchase.ml.mapper.sys.SysRolePermissionMapper;
import com.purchase.ml.mapper.sys.SysRoleUserMapper;
import com.purchase.ml.service.sys.ISysRoleService;
import com.purchase.ml.service.common.CommonSeqService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author kyyang
 * Created 2021-01-01
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private CommonSeqService commonSeqService;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public IPage<SysRole> sysRoleByPage(SysRoleQueryDto sysRoleQueryDto) {
        IPage<SysRole> page = new Page<>(sysRoleQueryDto.getPageIndex(),sysRoleQueryDto.getPageNum());
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        return sysRoleMapper.selectPage(page,wrapper);
    }

    @Override
    @Transactional
    public int sysRoleNew(SysRoleNewDto sysRoleNewDto) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleNewDto,sysRole);
        sysRole.setCreateTime(new Date());
        sysRole.setNum(commonSeqService.nextSeq(SysSeqNameEnum.SEQ_ROLE.getCode()).intValue());
        return sysRoleMapper.insert(sysRole);
    }

    @Override
    @Transactional
    public int sysRoleEdit(SysRoleEditDto sysRoleEditDto) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleEditDto,sysRole);
        sysRole.setUpdateTime(new Date());
        return sysRoleMapper.updateById(sysRole);
    }

    @Override
    @Transactional
    public int sysRoleDel(List<Long> ids) {
        int i = sysRoleMapper.deleteBatchIds(ids);
        //同时删除角色用户
        //同时删除角色权限
        for(Long id :ids){
            sysRoleUserMapper.deleteByRoleId(id);
            sysRolePermissionMapper.deleteByRoleId(id);
        }

        return i;
    }
}
